package com.iplay.实战java高并发程序设计.chapter3.c31;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author dangwu
 * @since 2021/10/27 5:22 下午
 */
public class TimeLock implements Runnable{
    public static ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {

        try {
            if (lock.tryLock(5, TimeUnit.SECONDS)){
                System.out.println("get lock success: "+Thread.currentThread().getName());
                Thread.sleep(6000);
            }else {
                System.out.println("get lock failed: "+Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if (lock.isHeldByCurrentThread()){
                System.out.println("release lock: "+Thread.currentThread().getName());
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        TimeLock timeLock = new TimeLock();
        Thread t1 = new Thread(timeLock,"1号线程");
        Thread t2 = new Thread(timeLock,"2号线程");
        t1.start();
        t2.start();
    }
}
